package com.itboye.eweilisten.util.dbutil;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.itboye.eweilisten.util.dbutil.model.UserInfo;

import java.util.ArrayList;

/**
 * Created by Mr.w on 2017/3/1.
 */

public class UserListManager {
    DBHelper dbHelper;
    private Context context;
    SQLiteDatabase db;
    private String tableName = "userinfo";

    public UserListManager(Context context) {
        this.context = context;
        dbHelper = new DBHelper(context, "user.db", 1, "create table " + tableName + " (id Integer primary key,username text)");
    }

    public ArrayList<UserInfo> queryUserName(String username) {
        db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        ArrayList<UserInfo> arrayUserName = new ArrayList<>();
        cursor = db.query(tableName, null, "username like ?", new String[]{"%" + username + "%"}, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                UserInfo userInfo = new UserInfo(cursor.getString(0), cursor.getString(1));
                arrayUserName.add(userInfo);
            }
            cursor.close();
        }
        db.close();
        return arrayUserName;
    }

    public long addUser(String username) {
        db = dbHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", username);
        long num = db.insert(tableName, null, cv);
        db.close();
        return num;
    }

    public long deleteUser(String id) {
        int innerId=Integer.parseInt(id);
        db = dbHelper.getWritableDatabase();
        long num = db.delete(tableName, "id=?", new String[]{innerId+""});
        db.close();
        return num;
    }
}
